﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Serialization;
using System.IO;
using ecdl.demo.model.expression;
using ecdl.demo.model.precondition;

namespace ecdl.demo.model.file {
    public class FileTaskSerializer : ExpressionSerializer {
        protected XmlSerializer serializer;

        public FileTaskSerializer() {

            AddType(typeof(CreateFile));
            AddType(typeof(CreateDirectory));
            AddPreconditions();
            serializer = CreateSerializer();
        }

        protected virtual void AddPreconditions() {
            AttributeOverrides.Add(typeof(FileTaskDTO), "Preconditions", GetPreconditionsAttributes());
        }

        protected override void RegisterTypes() {
            base.RegisterTypes();
            AddExpressionElementAttribute(typeof(FileExsistsConditionDTO), "FileExists");
            AddExpressionElementAttribute(typeof(FolderExistsConditionDTO), "FolderExists");
            AddExpressionElementAttribute(typeof(IsWriteProtectedConditionDTO), "IsWriteProtected");
            AddExpressionElementAttribute(typeof(FileExistsInZipConditionDTO), "FileExistsInZip");
        }

        protected virtual XmlAttributes GetPreconditionsAttributes() {
            return new XmlAttributes {
                XmlArray = new XmlArrayAttribute("Preconditions"),
                XmlArrayItems = {          
                    new XmlArrayItemAttribute("CreateFile", typeof(CreateFile)),
                    new XmlArrayItemAttribute("CreateDirectory", typeof(CreateDirectory))
                }
            };
        }

        protected override void AddOverrides() {
            base.AddOverrides();
            AddAttributeOverride(typeof(FileTaskDTO), "Expression", GetExpressionXmlElementAttributes());
        }

        public void Serialize(FileTaskCatalogue taskCatalogue, StreamWriter writer) {
            serializer.Serialize(writer, taskCatalogue);
        }

        public void Serialize(FileTaskCatalogue taskCatalogue, TextWriter writer) {
            serializer.Serialize(writer, taskCatalogue);
        }

        public FileTaskCatalogue Deserialize(StreamReader reader) {
            return (FileTaskCatalogue)serializer.Deserialize(reader);
        }

        public FileTaskCatalogue Deserialize(StringReader reader) {
            return (FileTaskCatalogue)serializer.Deserialize(reader);
        }
        
        protected override Type GetRootType() {
            return typeof(FileTaskCatalogue);
        }
    }
}
